package com.youedata.solr;


import com.youedata.util.StringUtil;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;

/**
 * 用于获取操作索引的对象。
 *
 */
public class SolrSingleClient {
	static Logger logger = Logger.getLogger(SolrSingleClient.class);
	//操作索引对象
	private volatile  static SolrSingleClient solrClient = null;

	private static HttpSolrClient testClient = null;
	//solr服务器Host地址
	private static String solrHost = "http://localhost:9090/solr/";
	//测试使用
	public static final String CORE_TEST = "test"; //测试使用

	/**
	 * 生成单例
	 * @return
	 */
	public static SolrSingleClient getInstance(){
		if(solrClient == null){
			synchronized (SolrSingleClient.class){
				solrClient = new SolrSingleClient();
			}
		}
		return solrClient;
	}

	/**
	 * 创建solr连接
	 * @param coreName
	 * @return
	 */
	public SolrClient getHttpSolrClient(String coreName){

		try {
			if(!StringUtil.isEmpty(coreName)){
				if(CORE_TEST.equals(coreName)){
					if(testClient == null){
						if(!solrHost.endsWith("/")){
							solrHost += "/";
						}
						String solrUrl = solrHost + coreName;
						testClient = new HttpSolrClient.Builder(solrUrl).build();
					}
					return testClient;

				}

			}
		} catch (Exception e) {
			logger.error("创建solr连接失败"+" errmsg:"+e.getMessage());
		}
		return null;
	}

	/**
	 * 提交并释放连接
	 * @param solrClient
	 */
	public static void commit(org.apache.solr.client.solrj.SolrClient solrClient){
		try{
			solrClient.commit();
		}catch(Exception e){
			logger.error("释放solr连接失败");
		}
	}

	/**
	 * 提交优化索引并释放连接
	 * @param solrClient
	 */
	public static void commitAndOptimize(org.apache.solr.client.solrj.SolrClient solrClient){
		try{
			solrClient.commit();
			solrClient.optimize();
		}catch(Exception e){
			logger.error("释放solr连接失败");
		}
	}

}
